<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="订单编号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单编号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="deviceNumber">
        <el-input
          v-model="queryParams.deviceNumber"
          placeholder="请输入设备编号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="currentStatus">
        <el-select
          v-model="queryParams.currentStatus"
          placeholder="设备状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.equipment_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['equipment:temperature:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equipment:temperature:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['equipment:temperature:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['equipment:temperature:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="60">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="设备编号" prop="deviceNumber" width="120" />
      <el-table-column label="订单名称" prop="orderNumber" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="当前温度（℃）" prop="currentTemperature" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="当前湿度（%RH）" prop="currentHumidity" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="当前经度" prop="latitudeX" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="当前纬度" prop="latitudeY" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.equipment_status" :value="scope.row.currentStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="绑定车辆(车牌号)" align="center" width="150">
        <template slot-scope="scope">
          <el-button v-if="!scope.row.lgVehicle" @click="handleUpdate(scope.row)" size="mini" type="primary" v-hasPermi="['equipment:temperature:updateVehicle']">绑定车辆</el-button>
          <el-tag v-if="scope.row.lgVehicle" type="success">{{ scope.row.lgVehicle.licensePlate }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <router-link :to="'/temgpsinfo/'+scope.row.id +'/'" class="link-type" style="margin-right: 15px;">
              <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
          >详细</el-button>
          </router-link>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['equipment:temperature:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['equipment:temperature:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设备编号" prop="deviceNumber">
          <el-input v-model="form.deviceNumber" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="订单编号" prop="orderNumber">
          <el-input v-model="form.orderNumber" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="温度（℃）" prop="currentTemperature">
          <el-input type="number" v-model="form.currentTemperature" placeholder="请输入温度" />
        </el-form-item>
        <el-form-item label="当前湿度（%RH）" prop="currentHumidity">
          <el-input type="number" v-model="form.currentHumidity" placeholder="请输入湿度" />
        </el-form-item>
        <el-form-item label="当前经度" prop="latitudeX">
          <el-input v-model="form.latitudeX" placeholder="请输入湿度" />
        </el-form-item>
        <el-form-item label="当前纬度" prop="latitudeY">
          <el-input v-model="form.latitudeY" placeholder="请输入湿度" />
        </el-form-item>
        <el-form-item label="状态" prop="currentStatus">
          <el-select
            v-model="form.currentStatus"
            placeholder="设备状态"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.equipment_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定车辆">
          <el-button
            v-if="form.boundId != 0 || form.boundId == undefined"
            @click="handleCancelBound(form.id)"
          size="mini"
          type="primary"
            v-hasPermi="['equipment:temperature:delBound']"
          >取消绑定</el-button>
          <Index v-if="form.boundId == 0 || form.boundId == undefined" :tid="tid" @close="handleCloseDialog"  @selected="handleVehicleSelected"></Index>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTemperature,
  getTemperature,
  updateTemperature,
  addTemperature,
  delTemperature,
  delBound
} from "@/api/equipment/temperature";
import Index from '@/views/equipment/temperature/vehicle/index.vue'

export default {
  components: {
    Index
  },
  name: "Role",
  dicts: ['equipment_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      tid: undefined,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      currentStatus: 1,
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 数据范围选项
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限"
        },
        {
          value: "2",
          label: "自定数据权限"
        },
        {
          value: "3",
          label: "本部门数据权限"
        },
        {
          value: "4",
          label: "本部门及以下数据权限"
        },
        {
          value: "5",
          label: "仅本人数据权限"
        }
      ],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: undefined,
        deviceNumber: undefined,
        currentStatus: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        orderNumber: [
          { required: true, message: "订单编号不能为空", trigger: "blur" }
        ],
        deviceNumber: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      listTemperature(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.roleList = response.rows;
          console.log(response)
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false,
        this.menuNodeAll = false,
        this.deptExpand = true,
        this.deptNodeAll = false,
        this.form = {
          roleId: undefined,
          orderNumber: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined
        };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 选择车辆后关闭弹窗 */
    handleCloseDialog() {
      this.open = false; // 关闭弹窗
      this.getList();    // 可选：刷新数据
    },
    // 处理车辆选择
    handleVehicleSelected(vehicleId) {
      // 这里可以更新表单中的车辆绑定信息
      // 示例：如果需要可以存储vehicleId到form中
      this.form.boundId = vehicleId;
      // 或者直接刷新列表数据
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDataScope":
          this.handleDataScope(row);
          break;
        case "handleAuthUser":
          this.handleAuthUser(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加角色";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const temperatureId = row.id || this.ids
      getTemperature(temperatureId).then(response => {
        this.form = response.data;
        this.tid = response.data.id
        this.form.currentStatus = this.form.currentStatus.toString();
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if(value !== '2') {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            this.form.updateBy = this.$store.getters.name
            updateTemperature(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemperature(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 取消绑定 */
    handleCancelBound(id) {
      this.$modal.confirm("确认要取消该绑定？").then(() => { // 改用箭头函数保持this指向
        return delBound({ id: id }); // 确保参数结构匹配接口要求
      }).then(() => {
        this.$modal.msgSuccess("解绑成功");
        this.open = false;  // 关闭弹窗
        this.getList();     // 重新加载数据
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const temperatureIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除谁被id为"' + temperatureIds + '"的数据项？').then(function() {
        return delTemperature(temperatureIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('equipment/temperature/export', {
        ...this.queryParams
      }, `GPSTemperature_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
